<template>
    <div class="chart-wrap">
       <div class="title">
          <span v-text="name"></span>
          <div class="tools">
            <el-select v-model="query.topnumber" placeholder="请选择">
              <el-option
                v-for="item in dateTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-date-picker
              v-model="query.startDate"
              type="date"
              placeholder="选择日期"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd">
            </el-date-picker>
            <el-date-picker
              v-model="query.endDate"
              type="date"
              placeholder="选择日期"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </div>
       </div>
       <div class="chart">
           <div ref="chart" class="content" ></div>
       </div>
    </div>
</template>

<script>
    import mixin from '../mixs/mixin.js';
    import echarts from "echarts";

    const  COLOR = ['#f96ec4','#6e8ef9','#00b113'];
    const  CATEGORYLIST = ['低','中','高'];
    export default {
        name: "chart_1" ,
        mixins: [mixin],
        props: {
          name: {
            type: String,
            default: '表名称'
          },
          category:{
            type: String,
            default: 'news' //分类 news,paper,patent
          }
        },
        data() {
          let startDate = new Date(`${new Date().getFullYear()}/1/1`).Format('yyyy-MM-dd');
          let endDate = new Date().Format('yyyy-MM-dd');
          return {
            apiUrl:'newtechanalyse/coWordAnalysis',
            dateTypeList:[
              {label:'10',value:'10'},
              {label:'20',value:'20'}
            ],
            query:{
              // startDate:startDate, //开始时间
              // endDate:endDate, //结束时间
              topnumber:'10', //Month,Day 查询时间类型
              category:this.category, //分类 News,Paper,Patent
            },
            nodes:[],
            edges:[],
          }
        },
        mounted(){
          this._initChart();
        },
        methods: {
          _initChart() {
             this.$nextTick(()=>{
                 if(!this._vmEchart){
                   this._vmEchart = echarts.init(this.$refs.chart);
                   this._vmEchart.showLoading();
                 }
             })
          },
          asyncDate(){
            //  异步加载数据  通用方法
            if(!this._vmEchart) return;
            this._vmEchart.clear();
            this._vmEchart.showLoading();
            this.api({
              url: this.apiUrl,
              method: "post",
              data:this.$qs.stringify({...this.query,topicId:this.navCurrentId})
            }).then(data => {
               this._formatDate(data)
            });
          },
          getDataURL(){
            // 获取图片base64
            return new Promise((resolve,reject)=>{
              if(!this._vmEchart){reject(); return; }
              resolve(this._vmEchart.getDataURL({
                backgroundColor: this.exportEchartBg
              }))
            });
          },
          _maxWeight(nodelist){
            let MAXWEIT = 1;
            nodelist.forEach(node => {
              if(!node.weight){
                node.weight = 1;
              }
              if(node.weight >= MAXWEIT){
                MAXWEIT = node.weight
              }
            })
            return MAXWEIT;
          },
          getItemProperty(weight,c_Weight){
            let colorList = COLOR;
            let categoryList = CATEGORYLIST;
            if(weight/c_Weight <= 0.33){
              return {color:colorList[0],category:categoryList[0]}
            }
            if(weight/c_Weight > 0.33 && weight/c_Weight <= 0.66){
              return {color:colorList[1],category:categoryList[1]}
            }
            if(weight/c_Weight > 0.66 ){
              return {color:colorList[2],category:categoryList[2]}
            }
          },
          _formatDate(data){
            // 根据不同的数据 配合不同的方法
            let $this = this;
            const MAXWEIGHT = $this._maxWeight(data.nodes);
            data.nodes.map(function(node) {
              let {category ,color } = $this.getItemProperty(node.weight,MAXWEIGHT);
              var datanode = {
                // x: parseInt(Math.random()*800),
                // y: parseInt(Math.random()*800),
                category:category,
                id: node.id + '',
                name: node.label,
                value: node.weight,
                symbolSize: 25,
                itemStyle: {
                  normal: {
                    color: color
                  }
                }
              };
              $this.nodes.push(datanode);
            });

            data.edges.map(function(edge) {
              var dataedge =  {
                source: edge.sourceID + '',
                target: edge.targetID + '',
                lineStyle:{
                  width: edge.size*2 > 6 ?  6 : edge.size*2,
                  color: '#000'
                },
                label: {
                  normal: {
                    show: true,
                    formatter: '频次'+edge.size
                  },
                  emphasis:{
                    show: true,
                  }
                },
              };
              $this.edges.push(dataedge);
            });
            this._setOption();
          },
          _setOption(){
             let $this = this;
             let option = {
               color:COLOR,
               animationDurationUpdate: 1500,
               animationEasingUpdate: "quinticInOut",
               tooltip: {},
               legend: [{
                 //selectedMode: 'single',
                 left:'10',
                 data: CATEGORYLIST,
                 textStyle:{
                   color:'#000'
                 }
               }],
               series: [
                 {
                   type: "graph",
                   layout: "force",
                   // progressiveThreshold: 700,
                   force : { //力引导图基本配置
                     //initLayout: ,//力引导的初始化布局，默认使用xy轴的标点
                     repulsion : 100,//节点之间的斥力因子。支持数组表达斥力范围，值越大斥力越大。
                     gravity : 0.03,//节点受到的向中心的引力因子。该值越大节点越往中心点靠拢。
                     edgeLength :80,//边的两个节点之间的距离，这个距离也会受 repulsion。[10, 50] 。值越小则长度越长
                     layoutAnimation : true
                     //因为力引导布局会在多次迭代后才会稳定，这个参数决定是否显示布局的迭代动画，在浏览器端节点数据较多（>100）的时候不建议关闭，布局过程会造成浏览器假死。
                   },
                   categories: CATEGORYLIST.map((item)=>{
                     return {
                       name: item
                     }
                   }),
                   data: $this.nodes,
                   draggable:true,
                   edges: $this.edges,
                   symbolSize: 30,
                   label: {
                     show:true,
                     emphasis: {
                       position: "inside",
                       show: true
                     }
                   },
                   roam: true,
                   focusNodeAdjacency: true,
                   lineStyle: {
                     color: 'source',
                     curveness: 0.3
                   }
                 }
               ]
             };

             this._vmEchart.hideLoading();
             this._vmEchart.setOption(option)
          }
        },


    }
</script>

<style lang="scss" scoped>
    .chart{
      position: relative;
      .content{
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
      }
    }

</style>
